import {
    COURSE_API
} from '@/API.js';

import hljs from 'highlight.js';
import parseHtml from '@/common/parseHtml';
import clike from 'highlight.js/lib/languages/c-like';
import 'highlight.js/styles/atom-one-light.css';

hljs.registerLanguage('clike', clike);

//返回是对应chapter的信息
export async function getChapterLesson(course_id, chapter_id) {
    let [err, res] = await uni.request({
        url: COURSE_API.transcript.url,
        method: COURSE_API.transcript.method,
        header: {
            'http-token': getApp().globalData.user.token
        },
        data: {
            course_id: course_id
        }
    });
    if (res.statusCode == 200) {
        let chapters = res.data.chapters;
        for (let chapter of chapters) {
            if (chapter.id == chapter_id) {
                // console.log(chapter, course_id);
                return chapter;
            }
        }
    } else {
        toast(res.data);
        return null;
    }
    if (err)
        toast(err);
}

//查询对应lesson的编程代码
export async function getSubmissonCode(course_id, chapter_lesson_id) {
    let [err, res] = await uni.request({
        url: COURSE_API.submissionCode.url,
        method: COURSE_API.submissionCode.method,
        header: {
            'http-token': getApp().globalData.user.token
        },
        data: {
            course_id,
            chapter_lesson_id
        }
    });
    console.log(res);
    if (res.statusCode == 200) {
        return res.data.code;
    } else {
        toast(res.data);
    }
    if (err)
        toast(err);
}

//返回所有code的lesson列表
export function getCodeLesson(chapter) {
    let lessons = chapter.lessons.reduce((pre, value) => {
        if (value.lesson_type == 'code' || value.lesson_type == 'challenge') {
            pre.push(value);
        }
        return pre;
    }, []);
    return lessons;
}

export function toast(title) {
    uni.showToast({
        icon: 'none',
        title
    });
}

//将代码文本解析为html
export function rawCodeToHtml(rawCode) {
    let lines = rawCode.split('\n');
    const maxLengthPerLine = 37;
    let html = lines.map((value) => {
        let code = '<li class="prog-list">';
        for (let i = 0; i < value.length; i += maxLengthPerLine) {
            if (i > 0) {
                code += '<li class="prog-wrap">';
            }
            code += hljs.highlight('clike', value.substr(i, maxLengthPerLine) + '\n').value;
            if (i > 0) {
                code += '</li>';
            }
        }
        return code + '</li>';
    });
    html = '<pre><code class="prog-code"><ul class="prog-ul">' + html.join('') + '</ul></code></pre>';
    return parseHtml(html);
}
